package run.bottle.common.entity;

import javax.persistence.*;
import java.util.Date;

/**
 * @author liyc
 * @date 2022-03-25
 */
@MappedSuperclass
public class BaseEntity {

    @Column(name = "CREATED_BY", nullable = false)
    private Long createdBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATED_TIME", nullable = false)
    private Date createdTime;

    @Column(name = "UPDATED_BY")
    private Long updatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "UPDATED_TIME")
    private Date updatedTime;

    @PrePersist
    protected void prePersist() {
        Date now = new Date();
        if (createdTime == null) {
            createdTime = now;
        }

        if (updatedTime == null) {
            updatedTime = now;
        }

        if (createdBy == null) {
            createdBy = -1L;
        }

        if (updatedBy == null) {
            updatedBy = -1L;
        }
    }

    @PreUpdate
    protected void preUpdate() {
        updatedTime = new Date();
    }

    @PreRemove
    protected void preRemove() {
        updatedTime = new Date();
    }

}
